package com.chinasofti.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        //1.打开通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2.绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(10000));
        //3.通道默认是阻塞(true)的,需要传递false,设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //4.经常查看一下有没有数据
        while (true){
             //如果有客户链接了,则在服务端内部创建一个客户通道,相当于
            //客户管道的延伸
            SocketChannel socketChannel=serverSocketChannel.accept();
            if (socketChannel != null){
                //如果不为空,则读取数据
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                /*
                整数:读到的有效字节数
                0:表示表示本次没有读到有效字节数
                负数:表示读到了末尾
                 */
                int len = socketChannel.read( byteBuffer);
                System.out.println(new  String(byteBuffer.array(),0,len));
                //释放资源
                socketChannel.close();
            }
        }
    }
}
